import { getItem, setItem } from '@/utils/storage'

// 保存状态到本地存储
function saveState (state) {
  console.log('==saveState', state)
  setItem('chatStore', state)
}

export default {
  namespaced: true,
  state: () => {
    const uuid = 1002
    const localState = getItem('chatStore') || {}
    console.log('==chat-state', localState)

    return {
      ...{
        history: [],
        active: uuid,
        chat: [{ uuid, data: [] }],
        usingContext: true
      },
      ...localState
    }
  },
  getters: {
    getChatHistoryByCurrentActive (state) {
      console.log('==getters-getChatHistoryByCurrentActive:')
      const index = state.history.findIndex(item => item.uuid === state.active)
      return index !== -1 ? state.history[index] : null
    },
    // 根据id获取对话信息
    getChatByUuid: state => uuid => {
      console.log('==getters-getChatByUuid:', uuid)
      if (uuid) {
        return state.chat.find(item => item.uuid === uuid)?.data || []
      } else {
        return state.chat.find(item => item.uuid === state.active)?.data || []
      }
    }
  },
  mutations: {
    SET_ACTIVE (state, uuid) {
      console.log('==SET_ACTIVE', uuid)
      state.active = uuid || 1002
      saveState(state)
    },
    ADD_HISTORY_ITEM (state, history) {
      state.history.unshift(history)
      saveState(state)
    },
    ADD_CHAT_ITEM (state, chatItem) {
      state.chat.unshift(chatItem)
      saveState(state)
    },
    DELETE_HISTORY_ITEM (state, uuid) {
      const index = state.history.findIndex(item => item.uuid === uuid)
      if (index !== -1) {
        state.history.splice(index, 1)
        saveState(state)
      }
    },
    DELETE_CHAT_ITEM (state, uuid) {
      const index = state.chat.findIndex(item => item.uuid === uuid)
      if (index !== -1) {
        state.chat.splice(index, 1)
        saveState(state)
      }
    },
    UPDATE_HISTORY_ITEM (state, { uuid, edit }) {
      const index = state.history.findIndex(item => item.uuid === uuid)
      if (index !== -1) {
        state.history[index] = { ...state.history[index], ...edit }
        saveState(state)
      }
    },
    APPEND_CHAT (state, { uuid, chat }) {
      const index = state.chat.findIndex(item => item.uuid === uuid)
      if (index !== -1) {
        state.chat[index].data.push(chat)
        saveState(state)
      }
    },
    UPDATE_CHAT (state, { uuid, index, chat }) {
      const chatIndex = state.chat.findIndex(item => item.uuid === uuid)
      if (chatIndex !== -1) {
        // 确保 data 数组存在且索引有效
        if (!state.chat[chatIndex].data || index >= state.chat[chatIndex].data.length) {
          console.error('==Invalid chat index or data array')
          return
        }

        const targetChat = state.chat[chatIndex].data[index]
        console.log('==targetChat', state.chat[chatIndex].data, index)
        if (!targetChat) {
          console.error('==Target chat item not found')
          return
        }

        // 处理思考状态
        if (targetChat.reasoning === '思考中...') {
          targetChat.reasoning = ''
        }
        // 合并内容
        const mergedChat = {
          ...targetChat,
          reasoning: chat.reasoning
            ? targetChat.reasoning + chat.reasoning
            : targetChat.reasoning,
          text: chat.text ? targetChat.text + chat.text : targetChat.text
        }

        state.chat[chatIndex].data[index] = mergedChat
        saveState(state)
      }
    }
  },
  actions: {
    createNewChat ({ commit, dispatch }, router) {
      console.log('==createNewChat', router)
      commit('SET_ACTIVE', 1002)
      return dispatch('reloadRoute', { uuid: '', router })
    },
    addHistory ({ commit, dispatch }, { history, chatData, router }) {
      console.log('==addHistory', history, chatData)
      commit('ADD_HISTORY_ITEM', history)
      commit('ADD_CHAT_ITEM', { uuid: history.uuid, data: chatData })
      commit('SET_ACTIVE', history.uuid)
      return dispatch('reloadRoute', { uuid: history.uuid, router })
    },
    deleteHistory ({ commit, dispatch, state }, { uuid, router }) {
      console.log('==deleteHistory', uuid)
      commit('DELETE_HISTORY_ITEM', uuid)
      commit('DELETE_CHAT_ITEM', uuid)

      if (state.active === uuid) {
        commit('SET_ACTIVE', 1002)
        return dispatch('reloadRoute', { uuid: '', router })
      }
    },
    updateHistory ({ commit }, { uuid, edit }) {
      console.log('==updateHistory', uuid, edit)
      commit('UPDATE_HISTORY_ITEM', { uuid, edit })
    },
    setActive ({ commit, dispatch }, { uuid, router }) {
      console.log('==setActive', uuid)
      commit('SET_ACTIVE', uuid || 1002)
      return dispatch('reloadRoute', { uuid, router })
    },
    reloadRoute ({ commit }, { uuid, router }) {
      console.log('==reloadRoute', uuid)
      // 状态已在mutations中自动保存
      console.log('==router:', router, '==uuid:', uuid)
      router.push(`/chat/${uuid}`)
    },
    addChatByUuid ({ commit, state }, { uuid, chat }) {
      console.log('==addChatByUuid', uuid, chat)
      if (!uuid || uuid === 0) {
        if (state.history.length === 0) {
          const newUuid = Date.now()
          commit('ADD_HISTORY_ITEM', {
            uuid: newUuid,
            title: chat.text?.substring(0, 10),
            isEdit: false,
            visible: false
          })
          commit('ADD_CHAT_ITEM', { uuid: newUuid, data: [chat] })
          commit('SET_ACTIVE', newUuid)
        } else {
          commit('APPEND_CHAT', { uuid: state.chat[0].uuid, chat })
          if (state.history[0].title === '新建会话') {
            commit('UPDATE_HISTORY_ITEM', {
              uuid: state.history[0].uuid,
              edit: { title: chat.text?.substring(0, 50) }
            })
          }
        }
      } else {
        const index = state.chat.findIndex(item => item.uuid === uuid)
        if (index !== -1) {
          commit('APPEND_CHAT', { uuid, chat })
          const historyIndex = state.history.findIndex(
            item => item.uuid === uuid
          )
          if (
            historyIndex !== -1 &&
            state.history[historyIndex].title === '新建会话'
          ) {
            commit('UPDATE_HISTORY_ITEM', {
              uuid,
              edit: { title: chat.text?.substring(0, 50) }
            })
          }
        }
      }
    },
    updateChatByUuid ({ commit, state }, { uuid, index, chat }) {
      console.log('==actions-updateChatByUuid', uuid, index, chat)
      const targetUuid = !uuid || uuid === 0 ? state.chat[0]?.uuid : uuid
      if (targetUuid) {
        commit('UPDATE_CHAT', {
          uuid: targetUuid,
          index,
          chat
        })
      }
    }
  }
}
